<template>
  <div class="card flex align-items-center justify-content-center bg">
    <Card style="width: 30rem">
      <template #title> 用户登录 </template>
      <template #content>
        <div class="card flex justify-content-center">
          <form @submit="onSubmit" class="flex flex-column gap-2 w-full">
            <span class="p-float-label">
              <!-- @vue-ignore -->
              <InputText v-model="username" type="text" :class="{ 'w-full': true, 'p-invalid': usernameError }"
                aria-describedby="text-error" />
              <label for="username">用户名</label>
            </span>
            <small class="p-error" id="text-error">{{ usernameError || '&nbsp;' }}</small>
            <span class="p-float-label">
              <!-- @vue-ignore -->
              <InputText v-model="password" type="text" :class="{ 'w-full': true, 'p-invalid': passwordError }"
                aria-describedby="text-error" />
              <label for="password">密码</label>
            </span>
            <small class="p-error" id="text-error">{{ passwordError }}</small>
            <span class="text-sm text-blue-500 cursor-pointer" @click="handleResgister">去注册</span>
            <Button type="submit" label="登录" />
          </form>
        </div>
      </template>
      <!-- <template #footer>
        <Button icon="pi pi-check" label="登录" />
        <Button icon="pi pi-times" label="返回" severity="secondary" style="margin-left: 0.5em" />
      </template> -->
    </Card>
  </div>

</template>

<script setup lang="ts">
import { Card, Button, InputText, useToast } from '@/utils/primevue'
import { useField, useForm } from 'vee-validate';
import * as Yup from 'yup';
import { useRouter } from 'vue-router'
import useChatStore from '@/stores/chat'

const toast = useToast();
const userStore = useChatStore()
const router = useRouter()

// 定义验证规则
const validationSchema = Yup.object({
  username: Yup.string().required('请输入用户名'),
  password: Yup.string().required('请输入密码'),
});

const { handleSubmit, resetForm } = useForm({ validationSchema, initialValues: { username: 'admin1', password: '123456' } });
const { value: username, errorMessage: usernameError } = useField('username');
const { value: password, errorMessage: passwordError } = useField('password');


const onSubmit = handleSubmit((values) => {
  userStore.login(values, () => {
    router.push('/chat/index')
    toast.add({ severity: 'success', summary: '登录成功', detail: values.username, life: 3000 });
    resetForm();
  })
});

const handleResgister = () => {
  console.log('99999')
  router.push('/chat/register')
}

</script>

<style scoped lang="scss">
.bg {
  width: 100%;
  height: 100%;
  background-image: url('../../../assets//images/image04.png');
  background-repeat: no-repeat;
  background-size: cover;
  // overflow: hidden;
}
</style>
